/**
 *
 */
package com.eit.eitsite.modules.sys.security;

import com.eit.eitsite.common.utils.SpringContextHolder;
import com.eit.eitsite.common.utils.StringUtils;
import com.eit.eitsite.modules.sys.entity.User;
import com.eit.eitsite.modules.sys.utils.UserUtils;
import com.zhuoyue.elmt.UserExtUtils;
import com.zhuoyue.elmt.dao.MaintenanceRecordSzDao;
import com.zhuoyue.elmt.dao.MaintenanceStaffDao;
import com.zhuoyue.elmt.entity.GgZgdw;
import com.zhuoyue.elmt.entity.MaintenanceStaff;
import com.zhuoyue.elmt.entity.UserExt;
import net.sf.json.JSONObject;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Service;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 表单验证（包含验证码）过滤类
 *
 * @author eit
 * @version 2014-5-19
 */
@Service
public class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc.FormAuthenticationFilter {

    public static final String DEFAULT_CAPTCHA_PARAM = "validateCode";
    public static final String DEFAULT_MOBILE_PARAM = "mobileLogin";
    public static final String DEFAULT_MESSAGE_PARAM = "message";
    public static final String DEFAULT_ORG_CODE = "orgcode";
    public static final String DEFAULT_REGPUSHID = "regpushid";

    private String captchaParam = DEFAULT_CAPTCHA_PARAM;
    private String mobileLoginParam = DEFAULT_MOBILE_PARAM;
    private String messageParam = DEFAULT_MESSAGE_PARAM;
    private String orgcodeParam = DEFAULT_ORG_CODE;
    private String regpushidParam = DEFAULT_REGPUSHID;

    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        String username = getUsername(request);
        String password = getPassword(request);
        if (password == null) {
            password = "";
        }
        boolean rememberMe = isRememberMe(request);
        String host = StringUtils.getRemoteAddr((HttpServletRequest) request);
        String captcha = getCaptcha(request);
        boolean mobile = isMobileLogin(request);
        String orgcode = getOrgcode(request);
        String regpushid = getRegpushid(request);
        return new UsernamePasswordToken(username, password.toCharArray(), rememberMe, host, captcha, mobile, orgcode, regpushid);
    }

    public String getCaptchaParam() {
        return captchaParam;
    }

    protected String getCaptcha(ServletRequest request) {
        return WebUtils.getCleanParam(request, getCaptchaParam());
    }

    public String getOrgcodeParam() {
        return orgcodeParam;
    }

    protected String getOrgcode(ServletRequest request) {
        return WebUtils.getCleanParam(request, getOrgcodeParam());
    }

    public String getMobileLoginParam() {
        return mobileLoginParam;
    }

    protected boolean isMobileLogin(ServletRequest request) {
        return WebUtils.isTrue(request, getMobileLoginParam());
    }

    public String getMessageParam() {
        return messageParam;
    }

    public String getRegpushidParam() {
        return regpushidParam;
    }

    protected String getRegpushid(ServletRequest request) {
        return WebUtils.getCleanParam(request, getRegpushidParam());
    }

    /**
     * 登录成功之后跳转URL
     */
    public String getSuccessUrl() {
        return super.getSuccessUrl();
    }

    @Override
    protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception {
        ////		Principal p = UserUtils.getPrincipal();
        ////		if (p != null && !p.isMobileLogin()){
        //			 WebUtils.issueRedirect(request, response, getSuccessUrl(), null, true);
        ////		}else{
        ////			super.issueSuccessRedirect(request, response);
        ////		}

        SystemAuthorizingRealm.Principal p = UserUtils.getPrincipal();
        if (p != null && !p.isMobileLogin()) {
            WebUtils.issueRedirect(request, response, getSuccessUrl(), null, true);
        } else {
            Map record2 = new HashMap();
            record2.put("id", "1");
            record2.put("message", "用户登录成功！");
            //            record2.put("request", request);
            //            record2.put("response", response);

            List<UserExt> userExtList = new ArrayList();
            UserExt userExt = new UserExt();
            User user = UserUtils.getUser();
            MaintenanceStaff maintenanceStaff = UserExtUtils.getMaintenanceStaff(user.getLoginName());
            GgZgdw ggZgdw = UserExtUtils.getGgZgdw(user.getCompany().getCode());

            // 如果维保人员信息没有regpushid的话
            // 如果维保人员信息有regpushid的话 但和传来的regpushid不一致
            if(maintenanceStaff != null) {
                if (StringUtils.isEmpty(maintenanceStaff.getRegpushid())) {
                    if (StringUtils.isNotEmpty(p.getRegpushid())) {
                        maintenanceStaff.setRegpushid(p.getRegpushid());
                        UserExtUtils.updateMaintenanceStaff(maintenanceStaff);
                    }
                } else if (StringUtils.isNotEmpty(p.getRegpushid()) && !p.getRegpushid().equals(maintenanceStaff.getRegpushid())) {
                    maintenanceStaff.setRegpushid(p.getRegpushid());
                    UserExtUtils.updateMaintenanceStaff(maintenanceStaff);
                }

                userExt.setId(maintenanceStaff.getId());
                userExt.setCertificateNo(maintenanceStaff.getCertificateNo());
                userExt.setRegpushid(maintenanceStaff.getRegpushid());
            }

            userExt.setPhoto(user.getPhoto());
            userExt.setLoginName(user.getLoginName());
            userExt.setName(user.getName());
            userExt.setFailureNum(UserExtUtils.statFailureReport(user.getLoginName()));
            userExt.setScore(UserExtUtils.getScore(user.getLoginName()));

            userExt.setMainMode(ggZgdw.getMainMode());
            userExt.setSignMode(ggZgdw.getSignMode());
            userExt.setSignLeaveMode(ggZgdw.getSignLeaveMode());
            userExt.setUploadDataMode(ggZgdw.getUploadDataMode());
            userExt.setMainUnitName(user.getCompany().getName());

            userExtList.add(userExt);
            record2.put("list", userExtList);

            JSONObject str = JSONObject.fromObject(record2);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(str.toString());
            //	super.issueSuccessRedirect(request, response);
        }


    }

    /**
     * 登录失败调用事件
     */
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        String className = e.getClass().getName(), message = "";
        if (IncorrectCredentialsException.class.getName().equals(className) || UnknownAccountException.class.getName().equals(className)) {
            message = "用户或密码错误, 请重试.";
        } else if (e.getMessage() != null && StringUtils.startsWith(e.getMessage(), "msg:")) {
            message = StringUtils.replace(e.getMessage(), "msg:", "");
        } else {
            message = "系统出现点问题，请稍后再试！";
            e.printStackTrace(); // 输出到控制台
        }
        request.setAttribute(getFailureKeyAttribute(), className);
        request.setAttribute(getMessageParam(), message);
        return true;
    }

}